package net.huazai.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.huazai.entity.UserLoginEntity;
import net.huazai.entity.UserRegisterEntity;
import net.huazai.enums.BizCodes;
import net.huazai.service.FileService;
import net.huazai.service.UserService;
import net.huazai.utils.ApiResult;
import net.huazai.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 11987
 */
@Api(tags = "用户微服务账号模块")
@RestController
@RequestMapping("/api/user/v1/")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 注入文件上传服务
     */
    @Autowired
    private FileService fileService;

    @ApiOperation("用户账号信息查询")
    @GetMapping("/userDetail")
    public Object userDetail() {
        UserVo userInfo = userService.getUserDetail();
        return ApiResult.doSuccess(userInfo);
    }

    /**
     * 上传用户头像
     * 默认文件大小 1M，超过报错
     * @param file  文件
     * @return 文件上传结果
     */
    @ApiOperation("用户头像上传")
    @PostMapping("/upload")
    public ApiResult uploadUserAvatar(
            @ApiParam(value = "文件上传", required = true)
            @RequestPart("file") MultipartFile file){
        String result = fileService.uploadUserAvatar(file);
        return result != null ? ApiResult.doSuccess(result)
                : ApiResult.doResult(BizCodes.USER_AVATAR_FILE_UPLOAD_ERROR);
    }

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public ApiResult register(@ApiParam("用户注册请求实体") @RequestBody UserRegisterEntity userRegisterEntity){
        return userService.register(userRegisterEntity);
    }

    /**
     * 用户登录
     * @param userLoginEntity 登录请求实体
     * @return 登录结果
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public ApiResult login(@ApiParam("用户登录请求实体") @RequestBody UserLoginEntity userLoginEntity) {
        return userService.login(userLoginEntity);
    }

    /**
     * 用户刷新 token
     * @param refreshToken 刷新 token
     * @param accessToken 访问 token
     * @return 刷新结果
     */
    @ApiOperation("用户刷新token")
    @PostMapping("/refresh")
    public ApiResult refreshToken(
            @ApiParam(value = "刷新 token")  @RequestParam(value = "refreshToken")
            String refreshToken
            , @ApiParam(value = "访问 token") @RequestParam(value = "accessToken")
            String accessToken) {
        Map<String, Object> params = new HashMap<>();
        params.put("refresh_token", refreshToken);
        params.put("access_token", accessToken);
        return userService.refreshToken(params);
    }
}
